<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>组态实时变量值查看</title>
    <link rel="stylesheet" href="../src/css/common.css">
</head>
<body>
<script src="../src/js/vue-3.5.min.js"></script>
<script src="../src/js/axios.min.js"></script>
<script src="../src/js/tools.js"></script>
<div id="app">
    <div class="left">
        <div class="tab">
            <button @click="pageTo('1')">数据推送</button>
            <button @click="pageTo('2')">读写变量</button>
        </div>
        <div class="page1" v-if="pageIndex === '1'">
            <div class="form-box">
                <div class="form-row">
                    <textarea v-model="addrs" placeholder="请输入变量地址,多个逗号隔开" style="width: 100%;height: 50px"></textarea>
                </div>
                <div class="form-row" style="display: flex;align-items: center">
                    <button @click="create_list">&nbsp;&nbsp;&nbsp;查 询&nbsp;&nbsp;&nbsp;</button>
                    <span style="font-size: 14px;font-weight: bold;color: green" v-if="ws_state==='已连接'">{{ws_state}}</span>
                    <span style="font-size: 14px;font-weight: bold;color: red" v-else>{{ws_state}}</span>
                </div>
            </div>
            <hr>
            <div class="form-box">
                <table>
                    <tbody>
                    <tr>
                        <th>变量地址</th>
                        <th>数据类型</th>
                        <th>变量值</th>
                        <th>时间</th>
                    </tr>
                    <tr v-for="(item,index) in record_list" :key="index">
                        <td>{{getAddr(item.addr).addr}}</td>
                        <td>{{getAddr(item.addr).spec_type}}</td>
                        <td>{{getAddr(item.addr).value}}</td>
                        <td>{{getAddr(item.addr).create_time}}</td>
                    </tr>
                    </tbody>
                </table>
            </div>
            <hr>
            <div class="form-box">
                <table>
                    <tbody>
                    <tr>
                        <th>变量地址</th>
                        <th>报警|恢复</th>
                        <th>当前值</th>
                        <th>对比值</th>
                        <th>时间</th>
                    </tr>
                    <tr v-for="(item,index) in alert_list" :key="index">
                        <td>{{item.base_addr}}</td>
                        <td>
                            <span v-if="item.is_recovery === 0" class="red">{{item.alert}}</span>
                            <span v-if="item.is_recovery === 1" class="green">已恢复</span>
                        </td>
                        <td>{{item.detail_obj.alert_value.toFixed(2)}}</td>
                        <td>{{item.detail_obj.compare_value.toFixed(2)}}</td>
                        <td>{{item.create_time}}</td>
                    </tr>
                    </tbody>
                </table>
            </div>
        </div>
        <div class="page2" v-if="pageIndex === '2'">
            <div class="form-row">
                <label>addr</label>
                <input type="text"  v-model="formData.addr" placeholder="" style="width: 100%" />
            </div>
            <div class="form-row">
                <label>value</label>
                <input type="number"  v-model.number="formData.value" placeholder="" style="width: 100%" />
            </div>
            <div class="form-row" style="display: flex;align-items: center">
                <button @click="variable_read">查看内存变量值</button>
                <button @click="mem_write">修改内存变量值</button>
                <button @click="variable_write">按帧协议修改值</button>
            </div>
        </div>
    </div>
    <div class="right">
        <pre>{{json_content}}</pre>
    </div>
</div>
<script>
    // 创建 Vue 3 应用实例
    const {createApp, ref, reactive, onMounted} = Vue;
    createApp({
        setup() {
            const pageIndex = ref("1")
            const addrs = ref("55-00-02-000,55-00-02-001")
            const record_list = ref([]) // 变量值记录
            const alert_list = ref([]) // 报警和恢复记录
            const json_content = ref("")
            const base = reactive({
                api_url: "",
                ws_url: "",
                token: ""
            })
            const formData = reactive({
                addr: "90-00-00-003",
                value: 0,
            })
            const pageTo = (index) => {
                pageIndex.value = index
            }
            const create_list = () => {
                // console.log("addrs = ",addrs.value)
                if (addrs.value !== "") {
                    let arr = addrs.value.split(",")
                    let tmp_list = []
                    for(let row of arr) {
                        tmp_list.push({
                            addr: row,
                            spec_type: "",
                            value: "",
                            create_time: ""
                        })
                    }
                    record_list.value = tmp_list
                }else {
                    record_list.value = []
                }
            }
            const jsonFormat = (obj) => {
                return JSON.stringify(obj, null, 4)
            }

            let socket = null
            const map = reactive({})
            const ws_state = ref("正在连接")
            const getAddr = (addr) => {
                if (!map[addr]) {
                    return {
                        addr: "未找到",
                        spec_type: "",
                        value: "",
                        create_time: ""
                    }
                }
                return map[addr]
            }
            const connectWebSocket = () => {
                socket = new WebSocket(base.ws_url);
                socket.onopen = function (res) {
                    console.log("连接成功");
                    ws_state.value= "已连接"
                }
                socket.onclose = function (e) {
                    ws_state.value= "连接失败或断开,3秒后重连"
                    setTimeout(() => {
                        ws_state.value= "正在尝试重连"
                        connectWebSocket()
                    },3000)
                }
                socket.onerror = function (err) {
                    console.log("WebSocket error observed", err);
                }
                socket.onmessage = function(e) {
                    let obj = JSON.parse(e.data)
                    if(obj.code === 2) {
                        let addr_list = JSON.parse(obj.data)
                        console.log("code2=",addr_list)
                        for(let row of addr_list) {
                            map[row.addr] = row
                        }
                        // console.log("map",map)
                    }else if (obj.code === 3) {
                        let info_list = JSON.parse(obj.data)
                        console.log("code3=",info_list)
                        for(let info of info_list) {
                            info.detail_obj = JSON.parse(info.detail)
                            alert_list.value.unshift(info)
                            if(alert_list.value.length > 10) {
                                alert_list.value.pop()
                            }
                        }
                    }
                };
            }

            const variable_read = () => {
                axios.post(base.api_url + '/admin/variable/mem_value_read', {
                    addr: formData.addr,
                }, {
                    headers: {
                        'Authorization': base.token, // 添加认证头
                    }
                }).then(res => {
                    if(res.data.code === 0) {
                        let info = res.data.data.info
                        json_content.value = jsonFormat({
                            field_name: info.field_name,
                            addr: info.addr,
                            spec_type: info.spec_type,
                            value: info.value,
                            endian: info.endian,
                            ratio: info.ratio,
                            opc_addr: info.opc_addr,
                        })
                    }else {
                        json_content.value = jsonFormat(res.data)
                    }
                }).catch(err => {
                    console.log("variable_read", err)
                })
            }
            const variable_write = () => {
                axios.post(base.api_url + '/admin/variable/write', {
                    addr: formData.addr,
                    value: formData.value,
                }, {
                    headers: {
                        'Authorization': base.token, // 添加认证头
                    }
                }).then(res => {
                    json_content.value = jsonFormat(res.data)
                }).catch(err => {
                    console.log("variable_write", err)
                })
            }
            const mem_write = () => {
                axios.post(base.api_url + '/admin/variable/mem_value_update', {
                    addr: formData.addr,
                    value: formData.value,
                }, {
                    headers: {
                        'Authorization': base.token, // 添加认证头
                    }
                }).then(res => {
                    json_content.value = jsonFormat(res.data)
                }).catch(err => {
                    console.log("variable_write", err)
                })
            }

            onMounted(() => {
                let page = getUrlParam("page")
                if(!page) {
                    pageIndex.value = "1"
                }else {
                    pageIndex.value = page
                }
                base.api_url = getLocalStorage("api_url")
                base.ws_url = getLocalStorage("ws_url")
                base.token = getLocalStorage("token")
                connectWebSocket()
            })
            return {
                addrs,
                record_list,
                alert_list,
                json_content,
                ws_state,
                pageIndex,
                formData,
                pageTo,
                create_list,
                getAddr,
                variable_read,
                mem_write,
                variable_write,
            };
        }
    }).mount('#app');
</script>
</body>
</html>